import React from 'react';
import './style/';
import {action, observable} from "mobx";
import {WeaTools,WeaLocaleProvider} from "ecCom";
import objectAssign from "object-assign";
import {message,Button, Checkbox} from "antd";
const getLabel = WeaLocaleProvider.getLabel;
import {getDefaultPathname, getLSValue, initLSValue, setLSValue} from "../../../portal4theme/util/loginUtil";
import * as LOGIN_API from "../../../portal4theme/apis/login";
import QRCode from 'qrcode.react';
import E7QRCode from './E7QRCode'
class E7Form extends React.Component {

    constructor(props) {
        super(props);
        this.getLoginInfo = this.getLoginInfo.bind(this)
        this.setStateAndCache = this.setStateAndCache.bind(this);
        this.getMultiLangs = this.getMultiLangs.bind(this);
        this.getLoginForm = this.getLoginForm.bind(this);
        this.onPasswordForget = this.onPasswordForget.bind(this);
        this.onRememberChange = this.onRememberChange.bind(this);
        this.onValidateCodeChange = this.onValidateCodeChange.bind(this);
        this.onLogin = this.onLogin.bind(this)

    }

    state = {
        seriesnum_: 0,
        queryParams : {
            logintype:'1'
        },
        multiLangs : getLSValue('login', 'multiLangs') || [],
        data:{
            isLogging: false,
            hasMultiLang: false,
            multiLangVisible: false,
            loginFormItems: [],
            loginFormHiddenItems: [],
            loginSetting: {},
            validateCode: '/weaver/weaver.file.MakeValidateCode?seriesnum_=0',
            loginType: getLSValue('login', 'loginType') || 'form',
            langId: getLSValue('login', 'langId') || '',
            langText: getLSValue('login', 'langText') || '',
            isRememberAccount: getLSValue('login', 'isRememberAccount') || false,
            isRememberPassword: getLSValue('login', 'isRememberPassword') || false,
            cacheAccount: getLSValue('login', 'cacheAccount') || '',
            cachePassword: getLSValue('login', 'cachePassword') || '',
            labelInfo:{}
        }

    }

    componentWillMount (){
        this.getMultiLangs()
        const queryParams = this.state.queryParams
        this.getLoginInfo(queryParams)

    }




    render(){
        //login
        const {data,multiLangs} =this.state


        //multilang

        const {langId, langText, hasMultiLang, multiLangVisible} = data;




        let multiLangListComp = '';
        if (multiLangVisible) {
            multiLangListComp = (
                <div className={"lr_multilang"} style={{'background-color':'#f3fbf9',color:'#646767','text-align':'left'}}>
                    <ul>
                        {
                            multiLangs.map(item => {
                                return (
                                    <li style={{'text-indent':'10px','height':'20px',cursor:'pointer','line-height':'20px','background-color':item.language==langText?'#4695c4':'',color:item.language==langText?'#fff':''}} onClick={() => {
                                        this.getLoginForm({langId: item.id});
                                        this.setStateData({langId: item.id, langText: item.language, multiLangVisible: false});
                                        $("#selectLan").css({color:'#000000','background-color':'transparent'})
                                    }}
                                    >
                                        {item.language}
                                    </li>
                                );
                            })
                        }
                    </ul>
                </div>
            );
        }

        //form

        const {
            isLogging,
            isRememberPW,
            isRememberAccount,
            isRememberPassword,
            cacheAccount,
            cachePassword,
            loginType,
            loginFormItems,
            loginFormHiddenItems,
            loginSetting = {},
            validateCode,
            qrcode
        } = data;


        const {needforgotpassword, validateCodeKey = ''} = loginSetting;
        const validateCodeSrc = validateCode + '&validateCodeKey=' + validateCodeKey;

        // onClick={() =>{ this.setStateData({multiLangVisible: false});$("#selectLan").css({color:'#D5E7E4','background-color':'transparent'})} }
        return (
            <div style={{width:'100%',height:'100%'}} onClick={() =>{ this.setStateDataSync({multiLangVisible: false});$("#selectLan").css({color:'#000000','background-color':'transparent'})} } >
                <div style={{'margin-left':'auto','margin-right':'auto','text-align':'center',height:'20px',width:'240px',position:'relative',color:'#000000'}}>
                    {
                        loginType == 'form' ? (
                            <div style={{display:'inline-block',position:'absolute',right:'12px',width:'30px','text-align':'center'}}>
                                <i className="icon-coms-Scan " style={{cursor:'pointer'}} id="qrcode"  title={getLabel(390755,'扫码登录')} src="/wui/theme/ecology8/page/images/login/qrcode_wev8.png" onClick={() => this.setStateAndCache('loginType', 'QRCode')}></i>
                            </div>
                        ):(
                            <div style={{display:'inline-block',position:'absolute',right:'12px',width:'30px','text-align':'center'}}>
                                <i className="icon-coms-Revoke2 "  style={{cursor:'pointer'}} title={this.labelObj().fh}  onClick={() => this.setStateAndCache('loginType', 'form')} style={{cursor:'pointer'}}></i>
                            </div>
                        )

                    }
                    {
                        hasMultiLang?(
                            <div id="selectLan"  style={{display:'inline-block',position:'absolute',right:'47px','z-index':'9999',color:'#000000',width:'80px'}}>
                                <span
                                    onClick={e => {
                                        e.preventDefault && e.preventDefault();
                                        e.stopPropagation && e.stopPropagation();
                                        this.setStateData({multiLangVisible: !multiLangVisible});
                                        $("#selectLan").css({color:'#646767','background-color':'#ecf4f7'})
                                    }}
                                    style={{cursor:'pointer'}}
                                >
                                    <span style={{display:'inline-block','padding-left':'10px',height:'20px','line-height':'20px'}}>{langText}</span>
                                    <span style={{display:'line-block','margin-left':'9px',height:'20px','line-height':'20px'}}>▼</span>
                                </span>
                                {multiLangListComp}
                            </div>
                        ):""
                    }


                </div>

                {
                    loginType == 'form' ?(
                        <div >
                            {
                                loginFormItems.map((item, index) => {
                                    let defaultValue = '';
                                    if (item.atype == 'account') {
                                        defaultValue = cacheAccount;
                                    } else if (item.atype == 'password') {
                                        defaultValue = cachePassword;
                                    }

                                    let itemComp = (

                                        <div style={{'margin-left':'auto','margin-right':'auto','text-align':'center',height:'30px',width:'240px',position:'relative','margin-bottom':'5px'}}>


                                            <label className="e9login-form-label" style={{'z-index':'999',position:'absolute',left:'16px','font-size':'14px',color:'#b2bdbd',width:'30px','line-height':'30px',display:defaultValue?'none':'inline'}} onClick={this.onLabelClick}>{item.label}</label>
                                            <input style={{'text-indent':'6px',position:'absolute',left:'10px',height:'30px',width:'215px',color:'#000000','font-size':'12px',border:'1px solid rgb(210, 210, 210)'}} onFocus={this.onInputFocus}  type={item.type} id={item.id} name={item.name} autoComplete="off"  defaultValue={defaultValue} onBlur={this.onInputBlue} />
                                        </div>

                                    );

                                    if (item.atype == 'validatecode') {
                                        itemComp = (
                                            <div style={{'margin-left':'auto','margin-right':'auto','text-align':'center',height:'30px',width:'240px',position:'relative'}}>

                                                <div style={{"width":'97px', height: "30px",float:'left', position: "relative",'margin-left':'11px'}}>
                                                    <label className="e9login-form-label"   style={{'text-align':'left','text-indent':'10px',left:'0px','z-index':'999',width:'97px',color:'#b2bdbd',position:'absolute','font-size':'14px','line-height':'30px',overflow:'hidden','text-overflow':'ellipsis','white-space': 'nowrap'}}  onClick={this.onLabelClick}>{item.label}</label>
                                                    <input onFocus={this.onValidataInputFocus} onBlur={this.onValidataInputBlur} style={{'text-indent':'10px',left:'0px',width:'97px',height:'30px',color:'#000000','font-size':'12px',border:'0px',position:'absolute'}} type={item.type} id={item.id} name={item.name}   onChange={this.onInputChange}/>
                                                </div>
                                                <div style={{float:'right','margin-right':"16px"}}>
                                                    <img src={validateCodeSrc} style={{height:'30px'}} alt="" onClick={this.onValidateCodeChange}/>
                                                </div>

                                            </div>
                                        );
                                    }

                                    return itemComp;
                                })
                            }
                            {
                                loginFormHiddenItems.map((item, index) => {
                                    return <div key={index} style={{display: 'none'}} dangerouslySetInnerHTML={{__html: item.html}}></div>;
                                })
                            }
                            <div style={{'margin-left':'auto','margin-right':'auto','text-align':'center',height:'32px','padding-top':'12px',width:'240px',position:'relative',color:"#8c8c8c"}}>
                                {
                                    needforgotpassword == '1' && (
                                        <div style={{float:'left','margin-left':'10px'}} title={this.labelObj().forgetPassword}>
                                            <span style={{cursor:'pointer'}} onClick={() => this.onPasswordForget()}>{this.labelObj().forgetPassword}</span>
                                        </div>
                                    )
                                }
                                <div style={{float:'right'}}>

                                    {
                                        isRememberPW == '1' ? (
                                            <div style={{display:'inline-block',cursor:'pointer'}} title={this.labelObj().rememberAccount}>
                                                <Checkbox checked={isRememberAccount} onChange={(e) => this.onRememberChange('account', e.target.checked)}>{this.labelObj().rememberAccount}</Checkbox>
                                            </div>
                                        ) : (
                                            ""
                                        )
                                    }
                                    {
                                        isRememberPW == '1' ? (
                                            <div style={{display:'inline-block',cursor:'pointer'}} title={this.labelObj().rememberPassword}>
                                                <Checkbox checked={isRememberPassword} onChange={(e) => this.onRememberChange('password', e.target.checked)}>{this.labelObj().rememberPassword}</Checkbox>
                                            </div>
                                        ):(
                                            ""
                                        )
                                    }

                                </div>


                            </div>

                            <div style={{'margin-left':'auto','margin-right':'auto','text-align':'center',height:'35px',width:'240px','margin-top':'5px'}}>
                                <input type="button" id="submit" name="submit"  onClick={this.onLogin} style={{background:"url('/wui/theme/ecology7/page/images/login/lg_login_sbmt_wev8.png') center center no-repeat",width:'76px',height:'35px',border:'0px','font-size':'14px','color':'rgb(87, 129, 151)','letter-spacing':'2px','font-family':'Arial, Helvetica, sans-serif, SimSun',cursor:'pointer',outline:'none'}}/>
                            </div>
                        </div>
                    ) : (
                        <E7QRCode state={this.state} labelObj={this.labelObj} getLoginForm={this.getLoginForm} setStateAndCache={this.setStateAndCache}></E7QRCode>
                    )
                }








            </div>
        );
    }

    labelObj() {
        const {langId, labelInfo} = this.state.data;
        return labelInfo['langid' + langId] || {};
    }

    onValidateCodeChange() {
        this.setState({seriesnum_:this.state.seriesnum_+1})
        setTimeout(() => this.setStateData({validateCode: `/weaver/weaver.file.MakeValidateCode?seriesnum_=${this.state.seriesnum_}`}), 50);
    }

    onRememberChange(type, checked) {
        const {isRememberAccount, isRememberPassword} = this.state.data;
        if ('account' == type) {
            this.setStateData({
                isRememberAccount: checked,
                isRememberPassword: !checked ? checked : isRememberPassword
            });
        } else if ('password' == type) {
            this.setStateData({
                isRememberAccount: checked ? checked : isRememberAccount,
                isRememberPassword: checked
            });
        }
    }




    onPasswordForget(params = {}) {
        const {langId = this.state.data.langId} = params;
        window.doLoginAction && window.doLoginAction('forgetPassword', {langid: langId});
    };

    onLabelClick(e) {
        jQuery(e.target.parentNode).find('input').focus();
    }
    onInputChange(e) {
        if (e.target.value) {
            jQuery(e.target.parentNode).find('.e9login-form-label').hide();
        } else {
            jQuery(e.target.parentNode).find('.e9login-form-label').show();
        }
    }

    onInputFocus(e) {
        if (!e.target.value) {
            jQuery(e.target.parentNode).find('.e9login-form-label').hide();
        }

    }

    onValidataInputFocus(e){
        if (!e.target.value) {
            jQuery(e.target.parentNode).find('.e9login-form-label').hide();
        }
    }

    onValidataInputBlur(e){
        if (!e.target.value) {
            jQuery(e.target.parentNode).find('.e9login-form-label').show();
        }
    }

    onInputBlue(e) {
        if (!e.target.value) {
            jQuery(e.target.parentNode).find('.e9login-form-label').show();
        }

    }

    getMultiLangs(params = {}) {
        LOGIN_API.getActiveLanguage(params).then((result) => {
            if (result.status == '1') {
                const {activeLanguageInfo, activeLanguageIds, languageIdentify, systemDefaultLang = {}} = result;
                this.setState({multiLangs:activeLanguageInfo})
                setLSValue('login', 'multiLangs', activeLanguageInfo);
                WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
                WeaTools.ls.set('languageIdentify', languageIdentify);

                // 当前状态中没有语言时，取默认语言
                if (!this.state.data.langId) {
                    const {id: langId = '7', language: langText = '简体中文'} = systemDefaultLang;
                    this.getLoginForm({langId});
                    this.setStateData({langId, langText});
                }
            }
        });
    }

    getLoginInfo(params = {}) {
        LOGIN_API.getLoginInfo(params).then((result) => {
            this.getLoginForm(params,result);

        });
    }

    getLoginForm(params = {},data={}) {
        const queryParams = this.state.queryParams;
        const {logintype = '1'} = queryParams;
        const {loginId = '', langId = this.state.data.langId} = params;

        if (langId) {
            window.doLoginAction && window.doLoginAction('getLoginForm', {
                queryParams: queryParams,
                logintype: logintype,
                loginid: loginId,
                langid: langId,
                callback: (result) => {
                    const {hasMultiLang = false, loginFormItems = [], loginFormHiddenItems = [], loginSetting = {}} = result;
                    this.setStateData(objectAssign({hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting},data));
                }
            });
        }
    }

    setStateAndCache(key, value) {
        this.setStateData({[key]: value});
        setLSValue('login', key, value);
    }


    setStateData = (temp)=>{
        const data = objectAssign({}, this.state.data,temp)
        this.setState({data:data});
    }


    setStateDataSync = (temp)=>{

        this.setState(function(state,props){
            const data = objectAssign({}, state.data,temp)
            return{data:data}
        });
    }


    onLogin() {
        const queryParams = this.state.queryParams;
        const {logintype = '1'} = queryParams;
        const {langId, langText, isRememberAccount, isRememberPassword, loginSetting} = this.state.data;

        this.setStateData({isLogging: true});
        window.doLoginAction && window.doLoginAction('login', {
            queryParams: WeaTools.getUrlParams(window.location),
            logintype: logintype,
            langid: langId,
            loginSetting: loginSetting,
            success: (username, password) => {
                jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

                let cacheAccount = '';
                let cachePassword = '';
                if (isRememberAccount) cacheAccount = username;
                if (isRememberPassword) cachePassword = password;
                this.setState({isRememberAccount, isRememberPassword, cacheAccount, cachePassword});

                setLSValue('login', 'langId', langId);
                setLSValue('login', 'langText', langText);
                setLSValue('login', 'cacheAccount', cacheAccount);
                setLSValue('login', 'cachePassword', cachePassword);
                setLSValue('login', 'isRememberAccount', isRememberAccount);
                setLSValue('login', 'isRememberPassword', isRememberPassword);

                initLSValue(username, langId);
                WeaTools.ls.set('languageidweaver', langId);

                // 登录成功回调
                let loginCallback = true;
                if (window.onLoginCallback && typeof window.onLoginCallback == 'function') {
                    loginCallback = window.onLoginCallback();
                }

                // 登录成功回调返回true时，继续标准跳转。
                if (loginCallback) {
                    if (logintype == '2') {
                        window.location.href = '/spa/crmPortal/mobx/index.html#/main';
                    } else {
                        window.location.href = '/wui/index.html?#/main';
                    }
                }
                this.setStateData({isLogging: false});
            },
            failure: (params = {}) => {
                if (params.reflashValidateCode) {
                    this.onValidateCodeChange();
                }
                this.getLoginForm();
                this.setStateData({isLogging: false});
            }
        });
    }


}
export default E7Form;